/*
 * Copyright (C) 2004, Velocityme Partnership
 * TaskStateMachineActions.java
 *
 * Created on 09 October 2004, 02:50
 */

package com.velocityme.www.interfaces.nodeactions;

import com.velocityme.entity.Role;
import com.velocityme.entity.TaskStateMachine;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import com.velocityme.session.TaskStateMachineLocal;
import com.velocityme.www.actionforms.nodeactionforms.TaskStateMachineActionForm;
import com.velocityme.www.dto.IdName;
import com.velocityme.www.utility.NodeUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author  Robert
 */
public class TaskStateMachineActions extends NodeActions {

    /** Creates a new instance of TaskStateMachineActions */
    public TaskStateMachineActions() {
    }

    @Override
    public ActionForward show(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        session.setAttribute("taskStateMachine", lookupTaskStateMachineBean().findTaskStateMachine(key, nodeId));
        return mapping.findForward("ACTION_DISPLAY");
    }

    @Override
    public ActionForward showCreate(ActionMapping mapping,
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        session.setAttribute("unassignedRolePairs", NodeUtil.getAllRolePairs(key));
        session.setAttribute("interestedRolePairs", new ArrayList<IdName>());
        TaskStateMachine taskStateMachine = new TaskStateMachine();
        taskStateMachine.setParentNode(lookupNodeBean().findNode(key, nodeId));
        session.setAttribute("taskStateMachine", taskStateMachine);
        return mapping.findForward("ACTION_EDIT");
    }

    @Override
    public ActionForward showEdit(ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        TaskStateMachine taskStateMachine = lookupTaskStateMachineBean().findTaskStateMachine(key, nodeId);
        session.setAttribute("taskStateMachine", taskStateMachine);
        Collection<IdName> interestedRolePairs = new ArrayList<IdName>();
        for (Role role: taskStateMachine.getInterestedRoles()) {
            interestedRolePairs.add(new IdName(role.getId(), role.getName()));
        }
        Collection<IdName> allRolePairs = NodeUtil.getAllRolePairs(key);
        allRolePairs.removeAll(interestedRolePairs);
        session.setAttribute("unassignedRolePairs", allRolePairs);
        session.setAttribute("interestedRolePairs", interestedRolePairs);
        return mapping.findForward("ACTION_EDIT");
    }

    @Override
    public ActionForward edit(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Long nodeId;
        if (request.getParameter("btnSubmit").equals("OK")) {
            TaskStateMachine taskStateMachine = (TaskStateMachine)session.getAttribute("taskStateMachine");
            ((TaskStateMachineActionForm)form).extractTaskStateMachine(key, taskStateMachine);
            if (taskStateMachine.getId() != null) {
                lookupTaskStateMachineBean().editTaskStateMachine(key, taskStateMachine);
            }
            else {
                taskStateMachine = lookupTaskStateMachineBean().createTaskStateMachine(key, taskStateMachine);
            }
            nodeId = taskStateMachine.getId();
        }
        // Cancel simply displays the original node again
        else {
            nodeId = (Long)session.getAttribute("nodeId");
        }
        request.setAttribute("nodeId", nodeId);
        return mapping.findForward("ACTION_SUCCESS");
    }

    private TaskStateMachineLocal lookupTaskStateMachineBean() {
        try {
            Context c = new InitialContext();
            return (TaskStateMachineLocal) c.lookup("java:comp/env/TaskStateMachineBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private NodeLocal lookupNodeBean() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
